﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using System.Web.Security;

namespace HRM
{
    public partial class frmUserInfo : Form
    {
        private DialogResult retVal;
        private string _userName = "";
        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
        UserClient _wcfUser;
        int _deptid = 0;

        bool isChange = false;
        public frmUserInfo(string UserName, string[] Args)
        {
            this.KeyPreview = true;
            InitializeComponent();
            retVal = DialogResult.Cancel;
            //LoadLaguage();
            txtFullName.Text = Args[0];
            txtAddress.Text = Args[1];
            txtPhone.Text = Args[2];
            _deptid = Convert.ToInt32(Args[3]);


            try
            {
                _wcfUser = Service.User();
                LoadRoleList();
                UISetting.LoadRegion(ref cboRegion);


                if (UserName.Trim().Length > 0)
                {
                    DataTable dt = _wcfUser.User_GetInfo(UserName.Trim()).Tables[0];

                    _userName = UserName.Trim();
                    txtUserName.ReadOnly = true;
                    txtUserName.BackColor = this.BackColor;
                    txtUserName.Text = UserName;
                    txtFullName.Text = dt.Rows[0]["FullName"].ToString();
                    txtEmail.Text = dt.Rows[0]["Email"].ToString();
                    txtConfirmPassword.Text = dt.Rows[0]["Password"].ToString();
                    txtPassword.Text = dt.Rows[0]["Password"].ToString();
                    lblPass.Text = dt.Rows[0]["Password"].ToString();
                    txtAddress.Text = dt.Rows[0]["Address"].ToString();
                    txtPhone.Text = dt.Rows[0]["Phone"].ToString();
                    cboRegion.SelectedValue = dt.Rows[0]["RegionCode"].ToString();
                    if (dt.Rows[0]["BranchID"] != null)
                        cboBranch.SelectedValue = Convert.ToInt32(dt.Rows[0]["BranchID"]);
                    if (dt.Rows[0]["DepartmentID"] != null)
                        cboDepartment.SelectedValue = Convert.ToInt32(dt.Rows[0]["DepartmentID"]);
                    lstRole.Items.Clear();
                    string[] strRole = _wcfUser.User_GetUserRoles(UserName);
                    foreach (string s in strRole)
                    {
                        if (s.Substring(0, 3).ToLower().Contains("hrm"))
                            lstRole.Items.Add(s);
                    }
                }
                else
                {
                    _userName = "";
                    txtUserName.Enabled = true;
                }
                isChange = false;

            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }

            btnNew.Enabled = btnSave.Enabled = Program.isAdmin;
        }

        private void LoadLaguage()
        {
            if (this.Tag != null)
                this.Text = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
            UpdateUI.Load_GroupBox(ref groupBox1);
        }

        private bool CheckValid()
        {
            bool returnValue = true;
            txtUserName.BackColor = Color.White;
            if (txtUserName.Text.Trim().Length == 0)
            {
                MessageBox.Show(Message.Username_IsEmpty, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUserName.Focus();
                return false;

            }
            if (txtPassword.Text.Trim().Length == 0)
            {
                MessageBox.Show(Message.Password_IsEmpty, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return false;
            }
            if (!txtPassword.Text.Equals(txtConfirmPassword.Text))
            {
                MessageBox.Show(Message.NewPwdOtherOldPwd, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtConfirmPassword.Focus();
                return false;
            }

            //if (lstRole.Items.Count == 0)
            //{
            //    MessageBox.Show(UpdateUI.GetString("chuachonquyentruycap"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    lstRole.Focus();
            //    return false;
            //}
            //if (Program.intBranchID > 0)
            //{
            //    if (cboBranch.SelectedIndex == 0 && cboDepartment.SelectedIndex == 0)
            //    {
            //        MessageBox.Show(Message.Branch_IsEmpty, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //        cboBranch.Focus();
            //        return false;
            //    }

            //}
            //if (Program.intBranchID > 0)
            //{
            //    if (cboDepartment.SelectedIndex == 0)
            //    {
            //        MessageBox.Show(Message.Department_IsEmpty, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //        cboDepartment.Focus();
            //        return false;
            //    }

            //}
            return returnValue;
        }

        private void LoadRoleList()
        {
            try
            {
                string[] strRole = _wcfUser.User_GetAllRoles();
                foreach (string s in strRole)
                {
                    if (s.Substring(0, 3).ToLower().Contains("hrm"))
                        cboRoles.Items.Add(s);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckValid())
                {
                    isChange = true;
                    return;
                }
                string BranchID = "0";
                if (cboBranch.SelectedValue != null)
                    BranchID = cboBranch.SelectedValue.ToString();
                string DepartmentID = "0";
                if (cboDepartment.SelectedValue != null)
                    DepartmentID = cboDepartment.SelectedValue.ToString();

                if (_userName.Trim().Length > 0)
                {
                    //if (_wcfUser.User_Exist(txtUserName.Text.Trim()))
                    //{
                    //    MessageBox.Show(Message.Username_IsExist, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //    txtUserName.Focus();
                    //    return;
                    //}
                    if (_wcfUser.User_Update(_userName, txtPassword.Text, txtEmail.Text, txtFullName.Text, txtAddress.Text, txtPhone.Text, BranchID, DepartmentID, "",cboRegion.SelectedValue.ToString()) == "")
                    {
                        if (Program.strUserName.ToLower() == _userName)
                        {
                            //Khởi tạo lại service sau khi đã đổi mật khẩu
                            //Program.strPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim(), "SHA1");
                            _wcfUser = Service.User();
                        }
                        foreach (object s in lstRole.Items)
                        {
                            if (!_wcfUser.User_IsUserInRole(_userName, s.ToString()))
                                _wcfUser.User_AddUserToRole(_userName, s.ToString());
                        }

                        string[] strRole = _wcfUser.User_GetUserRoles(_userName);
                        foreach (string s in strRole)
                        {
                            if (s.ToString().Substring(0, 3).ToLower().Contains("hrm"))
                                if (!lstRole.Items.Contains(s))
                                    _wcfUser.User_RemoveUserFromRole(_userName, s);
                        }


                        txtUserName.ReadOnly = true;
                        txtUserName.BackColor = this.BackColor;
                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("capnhatthanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        isChange = false;
                        retVal = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("capnhatkhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        isChange = true;
                    }
                }
                else
                {
                    if (_wcfUser.User_Exist(txtUserName.Text.Trim()))
                    {
                        MessageBox.Show(Message.Username_IsExist, UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUserName.Focus();
                        return;
                    }

                    string strRetVal = _wcfUser.User_Create(txtUserName.Text.Trim(), txtPassword.Text, txtEmail.Text, txtFullName.Text, txtAddress.Text, txtPhone.Text, cboBranch.SelectedValue.ToString(), cboDepartment.SelectedValue.ToString(), "",cboRegion.SelectedValue.ToString()).ToLower();
                    if (strRetVal == "success")
                    {
                        _userName = txtUserName.Text.Trim();

                        foreach (object s in lstRole.Items)
                        {
                            if (s.ToString().Substring(0, 3).ToLower().Contains("hrm"))
                                if (!_wcfUser.User_IsUserInRole(_userName, s.ToString()))
                                    _wcfUser.User_AddUserToRole(_userName, s.ToString());
                        }

                        txtUserName.ReadOnly = true;
                        txtUserName.BackColor = this.BackColor;
                        Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), UpdateUI.GetString("themmoithanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        isChange = false;
                        retVal = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("themmoikhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        isChange = true;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(UpdateUI.GetString("loi") + ":\n" + ex.Message + "\n" + UpdateUI.GetString("ghiloi"));
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAddRole_Click(object sender, EventArgs e)
        {
            if (cboRoles.SelectedItem != null && !lstRole.Items.Contains(cboRoles.SelectedItem.ToString()))
                lstRole.Items.Add(cboRoles.SelectedItem.ToString());
        }

        private void btnRemoveRole_Click(object sender, EventArgs e)
        {
            lstRole.Items.Remove(lstRole.SelectedItem);
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            _userName = "";
            txtUserName.ReadOnly = false;
            txtUserName.BackColor = Color.White;
            txtUserName.Text = "";
            txtFullName.Text = "";
            txtEmail.Text = "";
            txtConfirmPassword.Text = "";
            txtPassword.Text = "";
            txtAddress.Text = "";
            txtPhone.Text = "";
            lstRole.Items.Clear();
            txtUserName.Focus();


        }

        private void frmUserInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isChange)
            {
                if (MessageBox.Show(UpdateUI.GetString("bandathaydoidulieu") + "\n" + UpdateUI.GetString("coluutruockhithoatkhong"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                    if (isChange)
                        e.Cancel = true;
                    else
                        e.Cancel = false;
                }
            }
            _wcfUser.Close();
            this.DialogResult = retVal;
        }

        private void frmUserInfo_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    this.Dispose();
                    this.DialogResult = retVal;
                    this.Close();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
                case Keys.F4:
                    break;
            }

        }
        private void DataChanged(object sender, EventArgs e)
        {
            isChange = true;
        }
        private void cboBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            UISetting.LoadDepartment(ref cboDepartment, Convert.ToInt32(cboBranch.SelectedValue));
            if (_userName.Trim().Length == 0)
                cboDepartment.SelectedValue = _deptid;
        }

        private void cboRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            string _RegionCode = "";
            BranchClient _wcfBranch = Service.Branch();
            _RegionCode = cboRegion.SelectedValue.ToString();
            DataTable dt = _wcfBranch.Branch_GetByRegionCode(_RegionCode).Tables[0];
            UISetting.LoadBranchByRegionCode(ref cboBranch, _RegionCode);
        }
    }
}
